import { ref, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import demandApi from '../apis/demand';

export function useMyDemands() {
  const router = useRouter();

  // 响应式数据
  const demandList = ref([]);
  const originalDemandList = ref([]); // 存储原始数据用于过滤
  const loading = ref(false);
  const searchKeyword = ref('');
  const deleteDialogVisible = ref(false);
  const currentDeleteId = ref(null);
  const editDialogVisible = ref(false);
  const currentEditDemand = ref(null);

  // 分页数据
  const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });



  // 需求状态选项
  const statusOptions = [
    { label: '待审核', value: 0 },
    { label: '审核通过', value: 1 },
    { label: '审核拒绝', value: 2 },
    { label: '已发布', value: 3 },
    { label: '已接单', value: 4 },
    { label: '进行中', value: 5 },
    { label: '已完成', value: 6 },
    { label: '已关闭', value: 7 }
  ];
  
  // 接单状态文本映射
  const orderStatusMap = {
    0: '待确认',
    1: '已确认',
    2: '已拒绝',
    3: '已取消'
  };

  // 过滤后的需求列表
  const filteredDemands = computed(() => {
    if (!Array.isArray(demandList.value)) {
      return [];
    }
    return demandList.value.filter(demand => {
      const matchesKeyword = !searchKeyword.value || 
        demand.title?.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        demand.description?.toLowerCase().includes(searchKeyword.value.toLowerCase());
      return matchesKeyword;
    });
  });

  // 监听搜索关键词的变化
  watch(searchKeyword, () => {
    // 当搜索条件变化时，可以在这里添加额外的逻辑
    // 例如：重置分页、显示加载状态等
    pagination.value.currentPage = 1; // 重置到第一页
    loadDemands(); // 触发重新加载数据
  });

  // 重置筛选条件
  const resetFilters = () => {
    searchKeyword.value = '';
    pagination.value.currentPage = 1;
    loadDemands(); // 重置后重新加载数据
  };
  
  // 处理搜索
  const handleSearch = () => {
    pagination.value.currentPage = 1;
    loadDemands(); // 触发搜索
  };

  // 格式化预算
  const formatBudget = (budget) => {
    if (budget === null || budget === undefined) {
      return '面议';
    }
    return `¥${budget.toFixed(2)}`;
  };

  // 格式化日期
  const formatDate = (date) => {
    if (!date) return '未设置';
    const d = new Date(date);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
  };

  // 获取状态文本
  const getStatusText = (status) => {
    const option = statusOptions.find(opt => opt.value === status);
    return option ? option.label : '未知';
  };

  // 获取接单状态文本
  const getOrderStatusText = (status) => {
    return orderStatusMap[status] || '未知';
  };

  // 截断文本
  const truncateText = (text, maxLength) => {
    if (!text) return '';
    return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
  };

  // 判断是否可以删除
  const canDelete = (demand) => {
    // 只有待审核和已发布状态的需求可以删除
    return [0, 3].includes(demand.status);
  };

  // 加载需求列表
  const loadDemands = async () => {
    loading.value = true;
    try {
      // 实际项目中调用API，添加用户标识信息
      const response = await demandApi.getDemandList({
        pageNum: pagination.value.currentPage,
        pageSize: pagination.value.pageSize,
        keyword: searchKeyword.value || undefined,
        // 添加用户标识信息，帮助后端识别当前用户
        userId: localStorage.getItem('userId') || undefined,
        userType: localStorage.getItem('userType') || undefined
      });
      
      // 处理后端返回的Result格式数据
      let dataList = [];
      let totalCount = 0;
      
      if (response.code === 200) {
        // 确保数据是数组
        dataList = Array.isArray(response.data?.records || response.data?.list || []) ? 
          (response.data?.records || response.data?.list || []) : [];
        totalCount = response.data?.total || response.total || 0;
      }
      
      demandList.value = dataList;
      originalDemandList.value = [...dataList]; // 保存原始数据
      pagination.value.total = totalCount;
      
      // 已优先使用真实API接口，模拟数据保留为注释
      /*
      demandList.value = [
        {
          id: 1,
          userId: 1,
          userType: 1,
          title: '网站前端开发需求',
          description: '需要开发一个响应式网站前端，包含首页、产品展示、关于我们、联系我们等页面。要求使用Vue.js框架，UI设计精美，交互流畅。',
          budget: 5000.00,
          deadline: '2025-12-31T00:00:00',
          status: 4,
          auditRemark: null,
          auditTime: '2025-11-10T10:30:00',
          auditUserId: 1,
          publishTime: '2025-11-10T10:35:00',
          createTime: '2025-11-09T15:20:00',
          updateTime: '2025-11-10T10:35:00',
          acceptedEnterprise: {
            id: 1,
            name: '科技有限公司',
            description: '专注于软件开发的企业'
          },
          bidAmount: 4800.00,
          orderStatus: 1
        },
        {
          id: 2,
          userId: 1,
          userType: 1,
          title: '移动应用UI设计',
          description: '为一款社交类移动应用设计UI界面，需要包含登录注册、首页信息流、个人中心、消息通知等模块。要求设计风格现代简约，用户体验良好。',
          budget: 3000.00,
          deadline: '2025-12-15T00:00:00',
          status: 3,
          auditRemark: null,
          auditTime: '2025-11-08T09:15:00',
          auditUserId: 1,
          publishTime: '2025-11-08T09:20:00',
          createTime: '2025-11-07T14:45:00',
          updateTime: '2025-11-08T09:20:00'
        },
        {
          id: 3,
          userId: 1,
          userType: 1,
          title: '后端API开发',
          description: '开发一个电商平台的后端API系统，包含用户管理、商品管理、订单管理、支付系统等功能模块。要求使用Spring Boot框架，MySQL数据库，实现完整的业务逻辑。',
          budget: 10000.00,
          deadline: '2026-01-15T00:00:00',
          status: 1,
          auditRemark: '审核通过，等待发布',
          auditTime: '2025-11-11T11:00:00',
          auditUserId: 1,
          publishTime: null,
          createTime: '2025-11-10T16:30:00',
          updateTime: '2025-11-11T11:00:00'
        },
        {
          id: 4,
          userId: 1,
          userType: 1,
          title: '数据分析报告',
          description: '需要对公司过去一年的运营数据进行分析，生成详细的数据分析报告，包括用户增长趋势、销售数据分析、市场趋势预测等内容。',
          budget: 2000.00,
          deadline: '2025-11-25T00:00:00',
          status: 5,
          auditRemark: null,
          auditTime: '2025-11-05T14:20:00',
          auditUserId: 1,
          publishTime: '2025-11-05T14:25:00',
          createTime: '2025-11-04T10:15:00',
          updateTime: '2025-11-05T14:25:00',
          acceptedEnterprise: {
            id: 2,
            name: '数据科技公司',
            description: '专注于数据分析服务'
          },
          bidAmount: 2200.00,
          orderStatus: 1
        },
        {
          id: 5,
          userId: 1,
          userType: 1,
          title: 'Logo设计',
          description: '为新创立的教育培训机构设计一个专业、现代的Logo，要求简洁易识别，能够体现教育行业特色。',
          budget: 800.00,
          deadline: '2025-11-20T00:00:00',
          status: 0,
          auditRemark: null,
          auditTime: null,
          auditUserId: null,
          publishTime: null,
          createTime: '2025-11-12T09:00:00',
          updateTime: '2025-11-12T09:00:00'
        }
      ];
      demandList.value = mockData;
      originalDemandList.value = mockData;
      pagination.value.total = mockData.length;
      */
    } catch (error) {
      ElMessage.error('加载需求列表失败，请稍后重试');
      console.error('加载需求列表错误:', error);
      
      // 在API调用失败时使用模拟数据作为备用
      const mockData = [
        {
          id: 1,
          userId: 1,
          userType: 1,
          title: '网站前端开发需求',
          description: '需要开发一个响应式网站前端，包含首页、产品展示、关于我们、联系我们等页面。要求使用Vue.js框架，UI设计精美，交互流畅。',
          budget: 5000.00,
          deadline: '2025-12-31T00:00:00',
          status: 4,
          auditRemark: null,
          auditTime: '2025-11-10T10:30:00',
          auditUserId: 1,
          publishTime: '2025-11-10T10:35:00',
          createTime: '2025-11-09T15:20:00',
          updateTime: '2025-11-10T10:35:00',
          acceptedEnterprise: {
            id: 1,
            name: '科技有限公司',
            description: '专注于软件开发的企业'
          },
          bidAmount: 4800.00,
          orderStatus: 1
        },
        {
          id: 2,
          userId: 1,
          userType: 1,
          title: '移动应用UI设计',
          description: '为一款社交类移动应用设计UI界面，需要包含登录注册、首页信息流、个人中心、消息通知等模块。要求设计风格现代简约，用户体验良好。',
          budget: 3000.00,
          deadline: '2025-12-15T00:00:00',
          status: 3,
          auditRemark: null,
          auditTime: '2025-11-08T09:15:00',
          auditUserId: 1,
          publishTime: '2025-11-08T09:20:00',
          createTime: '2025-11-07T14:45:00',
          updateTime: '2025-11-08T09:20:00'
        },
        {
          id: 3,
          userId: 1,
          userType: 1,
          title: '后端API开发',
          description: '开发一个电商平台的后端API系统，包含用户管理、商品管理、订单管理、支付系统等功能模块。要求使用Spring Boot框架，MySQL数据库，实现完整的业务逻辑。',
          budget: 10000.00,
          deadline: '2026-01-15T00:00:00',
          status: 1,
          auditRemark: '审核通过，等待发布',
          auditTime: '2025-11-11T11:00:00',
          auditUserId: 1,
          publishTime: null,
          createTime: '2025-11-10T16:30:00',
          updateTime: '2025-11-11T11:00:00'
        },
        {
          id: 4,
          userId: 1,
          userType: 1,
          title: '数据分析报告',
          description: '需要对公司过去一年的运营数据进行分析，生成详细的数据分析报告，包括用户增长趋势、销售数据分析、市场趋势预测等内容。',
          budget: 2000.00,
          deadline: '2025-11-25T00:00:00',
          status: 5,
          auditRemark: null,
          auditTime: '2025-11-05T14:20:00',
          auditUserId: 1,
          publishTime: '2025-11-05T14:25:00',
          createTime: '2025-11-04T10:15:00',
          updateTime: '2025-11-05T14:25:00',
          acceptedEnterprise: {
            id: 2,
            name: '数据科技公司',
            description: '专注于数据分析服务'
          },
          bidAmount: 2200.00,
          orderStatus: 1
        },
        {
          id: 5,
          userId: 1,
          userType: 1,
          title: 'Logo设计',
          description: '为新创立的教育培训机构设计一个专业、现代的Logo，要求简洁易识别，能够体现教育行业特色。',
          budget: 800.00,
          deadline: '2025-11-20T00:00:00',
          status: 0,
          auditRemark: null,
          auditTime: null,
          auditUserId: null,
          publishTime: null,
          createTime: '2025-11-12T09:00:00',
          updateTime: '2025-11-12T09:00:00'
        }
      ];
      // 修复模拟数据赋值逻辑
      demandList.value = mockData;
      originalDemandList.value = [...mockData]; // 保存原始数据
      pagination.value.total = mockData.length;
    } finally {
      loading.value = false;
    }
  };

  // 跳转到发布需求页面
  const goToPublishDemand = () => {
    router.push('/publish-demand');
  };

  // 详情弹窗相关状态
  const detailDialogVisible = ref(false);
  const currentDetailDemand = ref(null);
  const isEditMode = ref(false);

  // 查看需求详情
  const viewDemandDetail = (demand) => {
    // 设置当前查看的需求（深拷贝避免直接修改原数据）
    currentDetailDemand.value = JSON.parse(JSON.stringify(demand));
    // 设置为查看模式
    isEditMode.value = false;
    // 显示详情弹窗
    detailDialogVisible.value = true;
  };

  // 切换到编辑模式
  const switchToEditMode = () => {
    if (!currentDetailDemand.value || ![0, 1, 3].includes(currentDetailDemand.value.status)) {
      ElMessage.warning('该状态的需求无法编辑');
      return;
    }
    isEditMode.value = true;
  };

  // 取消编辑
  const cancelEdit = () => {
    isEditMode.value = false;
    // 重新获取原始数据
    const originalDemand = demandList.value.find(item => item.id === currentDetailDemand.value.id);
    if (originalDemand) {
      currentDetailDemand.value = JSON.parse(JSON.stringify(originalDemand));
    }
  };

  // 编辑需求
  const editDemand = (demand) => {
    if (![0, 1, 3].includes(demand.status)) {
      ElMessage.warning('该状态的需求无法编辑');
      return;
    }
    // 设置当前编辑的需求（深拷贝避免直接修改原数据）
    currentEditDemand.value = JSON.parse(JSON.stringify(demand));
    // 显示编辑弹窗
    editDialogVisible.value = true;
  };

  // 保存编辑的需求
  const saveEditDemand = async () => {
    try {
      loading.value = true;
      // 确定要保存的需求对象（来自详情弹窗或编辑弹窗）
      const demandToSave = isEditMode.value ? currentDetailDemand.value : currentEditDemand.value;
      // 调用API更新需求
      await demandApi.updateDemand(demandToSave.id,demandToSave);
      
      // 更新本地数据
      const index = demandList.value.findIndex(item => item.id === demandToSave.id);
      if (index > -1) {
        demandList.value[index] = { ...demandToSave };
        originalDemandList.value[index] = { ...demandToSave };
      }
      
      ElMessage.success('需求更新成功');
      
      // 如果是从详情弹窗编辑的，切换回查看模式
      if (isEditMode.value) {
        isEditMode.value = false;
      } else {
        // 如果是从编辑弹窗编辑的，关闭弹窗
        editDialogVisible.value = false;
      }
    } catch (error) {
      console.error('更新需求失败:', error);
      ElMessage.error('更新需求失败，请重试');
    } finally {
      loading.value = false;
    }
  };

  // 删除需求确认
  const deleteDemandConfirm = (demand) => {
    currentDeleteId.value = demand.id;
    deleteDialogVisible.value = true;
  };

  // 确认删除
  const confirmDelete = async () => {
    try {
      // 调用API删除需求
      loading.value = true;
      await demandApi.deleteDemand(currentDeleteId.value);
      
      // 从列表中移除
      const index = demandList.value.findIndex(item => item.id === currentDeleteId.value);
      if (index > -1) {
        demandList.value.splice(index, 1);
        pagination.value.total = demandList.value.length;
      }
      
      // 同时从原始列表中移除
      const originalIndex = originalDemandList.value.findIndex(item => item.id === currentDeleteId.value);
      if (originalIndex > -1) {
        originalDemandList.value.splice(originalIndex, 1);
      }
      
      deleteDialogVisible.value = false;
      ElMessage.success('需求删除成功');
    } catch (error) {
      console.error('删除需求失败:', error);
      ElMessage.error('删除需求失败，请稍后重试');
      
      // 注释掉模拟删除操作，只在API调用成功时更新UI
      // 如果需要在API失败时仍然更新UI，可以取消下面的注释
      /*
      const index = demandList.value.findIndex(item => item.id === currentDeleteId.value);
      if (index > -1) {
        demandList.value.splice(index, 1);
        pagination.value.total = demandList.value.length;
      }
      
      const originalIndex = originalDemandList.value.findIndex(item => item.id === currentDeleteId.value);
      if (originalIndex > -1) {
        originalDemandList.value.splice(originalIndex, 1);
      }
      deleteDialogVisible.value = false;
      ElMessage.success('需求删除成功');
      */
    } finally {
      loading.value = false;
    }
  };

  // 查看订单详情
  const viewOrderDetails = (demand) => {
    // 跳转到订单详情页或打开详情对话框
    ElMessage.info('订单详情功能开发中');
  };

  // 分页大小变化
  const handleSizeChange = (size) => {
    pagination.value.pageSize = size;
    loadDemands();
  };

  // 页码变化
  const handleCurrentChange = (current) => {
    pagination.value.currentPage = current;
    loadDemands();
  };

  return {
    demandList,
    loading,
    searchKeyword,
    deleteDialogVisible,
    currentDeleteId,
    editDialogVisible,
    currentEditDemand,
    detailDialogVisible,
    currentDetailDemand,
    isEditMode,
    pagination,
    filteredDemands,
    formatBudget,
    formatDate,
    getStatusText,
    getOrderStatusText,
    truncateText,
    canDelete,
    loadDemands,
    resetFilters,
    handleSearch,
    goToPublishDemand,
    viewDemandDetail,
    switchToEditMode,
    cancelEdit,
    editDemand,
    saveEditDemand,
    deleteDemandConfirm,
    confirmDelete,
    viewOrderDetails,
    handleSizeChange,
    handleCurrentChange
  };
}